//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package net.mingsoft.mdiy.action;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import java.sql.Clob;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.mingsoft.base.entity.BaseEntity;
import net.mingsoft.base.entity.ResultData;
import net.mingsoft.base.util.SqlInjectionUtil;
import net.mingsoft.basic.annotation.LogAnn;
import net.mingsoft.basic.bean.EUListBean;
import net.mingsoft.basic.constant.e.BusinessTypeEnum;
import net.mingsoft.basic.util.BasicUtil;
import net.mingsoft.basic.util.StringUtil;
import net.mingsoft.mdiy.bean.ModelJsonBean;
import net.mingsoft.mdiy.biz.IModelBiz;
import net.mingsoft.mdiy.constant.e.ModelCustomTypeEnum;
import net.mingsoft.mdiy.entity.ModelEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

@Api(
        tags = {"后端-自定义模块接口"}
)
@Controller("coMdiyModelAction")
@RequestMapping({"/${ms.manager.path}/mdiy/model"})
public class ModelAction extends BaseAction {
    @Autowired
    private IModelBiz modelBiz;
    private Pattern filePattern = Pattern.compile("(src|href)=\"(upload/.*?(png|jpg|gif))");

    public ModelAction() {
    }

    @ApiIgnore
    @GetMapping({"/index"})
    public String index(HttpServletResponse response, HttpServletRequest request) {
        return "/mdiy/model/index";
    }

    @ApiIgnore
    @GetMapping({"/form"})
    public String form(@ModelAttribute ModelEntity modelEntity, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap) {
        if (modelEntity.getId() != null) {
            BaseEntity _modelEntity = (BaseEntity)this.modelBiz.getById(modelEntity.getId());
            modelMap.addAttribute("modelEntity", _modelEntity);
        }

        return "/mdiy/model/form";
    }

    @ApiOperation("查询自定义模型列表接口")
    @ApiImplicitParams({@ApiImplicitParam(
            name = "modelName",
            value = "模型名称",
            required = false,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "modelTableName",
            value = "模型表名",
            required = false,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "appId",
            value = "应用编号",
            required = false,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "modelJson",
            value = "json",
            required = false,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "createBy",
            value = "创建人",
            required = false,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "createDate",
            value = "创建时间",
            required = false,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "updateBy",
            value = "修改人",
            required = false,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "updateDate",
            value = "修改时间",
            required = false,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "del",
            value = "删除标记",
            required = false,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "id",
            value = "编号",
            required = false,
            paramType = "query"
    )})
    @GetMapping({"/list"})
    @ResponseBody
    public ResultData list(@ModelAttribute @ApiIgnore ModelEntity modelEntity, HttpServletResponse response, HttpServletRequest request, @ApiIgnore ModelMap model, BindingResult result) {
        modelEntity.setModelCustomType(ModelCustomTypeEnum.MODEL.getLabel());
        BasicUtil.startPage();
        List modelList = this.modelBiz.query(modelEntity);
        return ResultData.build().success(new EUListBean(modelList, (int)BasicUtil.endPage(modelList).getTotal()));
    }

    @ApiOperation("查询自定义模型数据接口")
    @GetMapping({"/data"})
    @ResponseBody
    public ResultData data(String modelId, String linkId, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap) {
        SqlInjectionUtil.filterContent(new String[]{linkId});
        ModelEntity model = (ModelEntity)this.modelBiz.getById(modelId);
        Map data = null;
        if (StringUtils.isBlank(linkId)) {
            linkId = "0";
        }

        if (ObjectUtil.isNotNull(model)) {
            List<Map> listMap = (List)this.modelBiz.excuteSql(StrUtil.format("select * from {} where link_id = '{}'", new Object[]{model.getModelTableName(), linkId}));
            if (listMap.size() > 0) {
                data = new HashMap();

                Object o;
                Object _o;
                for(Iterator var9 = ((Map)listMap.get(0)).keySet().iterator(); var9.hasNext(); data.put(this.getCamelCaseString(o.toString(), false), _o)) {
                    o = var9.next();
                    _o = ((Map)listMap.get(0)).get(o);
                    if (_o instanceof Clob) {
                        _o = StringUtil.clobStr((Clob)_o);
                    }
                }
            }
        }

        return ResultData.build().success(data);
    }

    private String getCamelCaseString(String inputString, boolean firstCharacterUppercase) {
        StringBuilder sb = new StringBuilder();
        boolean nextUpperCase = false;

        for(int i = 0; i < inputString.length(); ++i) {
            char c = inputString.charAt(i);
            switch(c) {
                case ' ':
                case '#':
                case '$':
                case '&':
                case '-':
                case '/':
                case '@':
                case '_':
                    if (sb.length() > 0) {
                        nextUpperCase = true;
                    }
                    break;
                default:
                    if (nextUpperCase) {
                        sb.append(Character.toUpperCase(c));
                        nextUpperCase = false;
                    } else {
                        sb.append(Character.toLowerCase(c));
                    }
            }
        }

        if (firstCharacterUppercase) {
            sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
        }

        return sb.toString();
    }

    @ApiOperation("保存模型接口")
    @LogAnn(
            title = "保存模型",
            businessType = BusinessTypeEnum.INSERT
    )
    @PostMapping({"/data/save"})
    @ResponseBody
    public ResultData save(String linkId, String modelId, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap) {
        SqlInjectionUtil.filterContent(new String[]{linkId});
        ModelEntity model = (ModelEntity)this.modelBiz.getById(modelId);
        if (ObjectUtil.isNotNull(model) && StringUtils.isNotBlank(linkId)) {
            List<Map> listMap = (List)this.modelBiz.excuteSql(StrUtil.format("select * from {} where link_id = '{}'", new Object[]{model.getModelTableName(), linkId}));
            if (CollUtil.isNotEmpty(listMap)) {
                return ResultData.build().error(linkId);
            } else {
                Map<String, Object> requestMap = BasicUtil.assemblyRequestMap();
                Map fieldMap = model.getFieldMap();
                HashMap<String, Object> fields = new HashMap();
                Iterator var11 = requestMap.keySet().iterator();

                while(var11.hasNext()) {
                    String s = (String)var11.next();
                    if (fieldMap.containsKey(s)) {
                        try {
                            DateTime dateTime = DateUtil.parseDateTime(requestMap.get(s).toString());
                            fields.put(fieldMap.get(s).toString(), dateTime);
                        } catch (Exception var14) {
                            fields.put(fieldMap.get(s).toString(), requestMap.get(s));
                        }
                    }
                }

                fields.put("CREATE_DATE", new Date());
                fields.put("UPDATE_DATE", new Date());
                fields.put("CREATE_BY", BasicUtil.getManager().getId());
                fields.put("LINK_ID", linkId);
                if (model.getModelIdType() == 0) {
                    Snowflake snowflake = IdUtil.getSnowflake();
                    fields.put("ID", snowflake.nextId());
                }

                this.modelBiz.insertBySQL(model.getModelTableName(), fields);
                return ResultData.build().success(linkId);
            }
        } else {
            return ResultData.build().error(linkId);
        }
    }

    @ApiOperation("更新模型接口")
    @LogAnn(
            title = "更新模型",
            businessType = BusinessTypeEnum.UPDATE
    )
    @PostMapping({"/data/update"})
    @ResponseBody
    public ResultData update(String linkId, String modelId, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap) {
        SqlInjectionUtil.filterContent(new String[]{linkId});
        ModelEntity model = (ModelEntity)this.modelBiz.getById(modelId);
        if (ObjectUtil.isNotNull(model) && StringUtils.isNotBlank(linkId)) {
            Map<String, Object> requestMap = BasicUtil.assemblyRequestMap();
            Map fieldMap = model.getFieldMap();
            HashMap<String, Object> fields = new HashMap();
            Iterator var10 = requestMap.keySet().iterator();

            while(var10.hasNext()) {
                String s = (String)var10.next();
                if (fieldMap.containsKey(s)) {
                    fields.put(fieldMap.get(s).toString(), requestMap.get(s));
                }
            }

            Map where = new HashMap();
            where.put("LINK_ID", linkId);
            List<Map> listMap = (List)this.modelBiz.excuteSql(StrUtil.format("select * from {} where link_id = '{}'", new Object[]{model.getModelTableName(), linkId}));
            if (CollUtil.isEmpty(listMap)) {
                fields.put("LINK_ID", linkId);
                fields.put("CREATE_DATE", new Date());
                fields.put("UPDATE_DATE", new Date());
                fields.put("CREATE_BY", BasicUtil.getManager().getId());
                this.modelBiz.insertBySQL(model.getModelTableName(), fields);
            } else {
                fields.put("UPDATE_DATE", new Date());
                fields.put("UPDATE_BY", BasicUtil.getManager().getId());
                this.modelBiz.updateBySQL(model.getModelTableName(), fields, where);
            }

            return ResultData.build().success(linkId);
        } else {
            return ResultData.build().error(linkId);
        }
    }

    @ApiOperation("查询自定义模型接口")
    @ApiImplicitParams({@ApiImplicitParam(
            name = "modelName",
            value = "模型名称",
            required = false,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "modelTableName",
            value = "模型表名",
            required = false,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "appId",
            value = "应用编号",
            required = false,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "modelJson",
            value = "json",
            required = false,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "createBy",
            value = "创建人",
            required = false,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "createDate",
            value = "创建时间",
            required = false,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "updateBy",
            value = "修改人",
            required = false,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "updateDate",
            value = "修改时间",
            required = false,
            paramType = "query"
    )})
    @GetMapping({"/get"})
    @ResponseBody
    public ResultData get(@ApiIgnore ModelEntity modelEntity, HttpServletResponse response, HttpServletRequest request) {
        if (modelEntity == null && StringUtils.isEmpty(modelEntity.getModelName())) {
            return ResultData.build().error(this.getResString("err.error", new String[]{this.getResString("model.name")}));
        } else {
            modelEntity.setModelCustomType(ModelCustomTypeEnum.MODEL.getLabel());
            ModelEntity model = (ModelEntity)this.modelBiz.getOne(new QueryWrapper(modelEntity));
            return ResultData.build().success(model);
        }
    }

    @ApiOperation("导入自定义模型接口")
    @ApiImplicitParams({@ApiImplicitParam(
            name = "modelJson",
            value = "json",
            required = true,
            paramType = "query"
    )})
    @LogAnn(
            title = "导入自定义模型",
            businessType = BusinessTypeEnum.INSERT
    )
    @PostMapping({"/importJson"})
    @ResponseBody
    @RequiresPermissions({"mdiy:model:importJson"})
    public ResultData importJson(@ModelAttribute @ApiIgnore ModelEntity modelEntity, HttpServletResponse response, HttpServletRequest request, BindingResult result) {
        if (StringUtils.isBlank(modelEntity.getModelJson())) {
            return ResultData.build().error(this.getResString("err.empty", new String[]{this.getResString("model.json")}));
        } else {
            modelEntity.setModelCustomType(ModelCustomTypeEnum.MODEL.getLabel());
            new ModelJsonBean();

            ModelJsonBean modelJsonBean;
            try {
                modelJsonBean = (ModelJsonBean)JSONUtil.toBean(modelEntity.getModelJson(), ModelJsonBean.class);
            } catch (Exception var7) {
                return ResultData.build().error(this.getResString("err.error", new String[]{this.getResString("model.json")}));
            }

            return this.modelBiz.importModel(ModelCustomTypeEnum.MODEL.getLabel(), modelJsonBean, modelEntity.getModelType()) ? ResultData.build().success() : ResultData.build().error(this.getResString("err.exist", new String[]{this.getResString("table.name")}));
        }
    }

    @ApiOperation("更新导入自定义模型")
    @ApiImplicitParams({@ApiImplicitParam(
            name = "modelJson",
            value = "json",
            required = true,
            paramType = "query"
    )})
    @LogAnn(
            title = "更新自定义模型",
            businessType = BusinessTypeEnum.INSERT
    )
    @PostMapping({"/updateJson"})
    @ResponseBody
    @RequiresPermissions({"mdiy:model:update"})
    public ResultData updateJson(@ModelAttribute @ApiIgnore ModelEntity modelEntity, HttpServletResponse response, HttpServletRequest request, BindingResult result) {
        if (StringUtils.isBlank(modelEntity.getModelJson())) {
            return ResultData.build().error(this.getResString("err.empty", new String[]{this.getResString("model.json")}));
        } else if (StringUtils.isBlank(modelEntity.getId())) {
            return ResultData.build().error(this.getResString("err.empty", new String[]{this.getResString("id")}));
        } else {
            ModelJsonBean modelJsonBean = null;

            try {
                modelJsonBean = (ModelJsonBean)JSONUtil.toBean(modelEntity.getModelJson(), ModelJsonBean.class);
            } catch (Exception var7) {
                return ResultData.build().error(this.getResString("err.error", new String[]{this.getResString("model.json")}));
            }

            return this.modelBiz.updateConfig(modelEntity.getId(), modelJsonBean, modelEntity.getModelType()) ? ResultData.build().success() : ResultData.build().error(this.getResString("err.exist", new String[]{this.getResString("table.name")}));
        }
    }

    @ApiOperation("批量删除自定义模型列表接口")
    @LogAnn(
            title = "批量删除自定义模型",
            businessType = BusinessTypeEnum.DELETE
    )
    @PostMapping({"/delete"})
    @ResponseBody
    @RequiresPermissions({"mdiy:model:del"})
    public ResultData delete(@RequestBody List<ModelEntity> models, HttpServletResponse response, HttpServletRequest request) {
        List<String> ids = (List)models.stream().map(ModelEntity::getId).collect(Collectors.toList());
        this.modelBiz.delete(ids);
        return ResultData.build().success();
    }

    @ApiOperation("自定义页面输出")
    @GetMapping({"/formTmpl"})
    public String formTmpl(String url, String formUrls, String model, String id, HttpServletRequest request) {
        request.setAttribute("url", url);
        request.setAttribute("formUrls", formUrls);
        request.setAttribute("model", model);
        return "/mdiy/model/form-tmpl";
    }
}
